using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace Library
{
    public class Database : IStorable
    {
        
        private string clientPath = @"clients.txt";
        private string bookPath = @"books.txt";
        private string newspaperPath = @"newspapers.txt";
        private string magazinePath = @"magazines.txt";
        private string tenantPath = @"tenantData.txt";

        public void StoreBook(Book newReading)
        {
            bool fileCreated = CreateFileIfNotExists(this.bookPath);
            if (fileCreated)
            {
                using(StreamWriter writer = new StreamWriter(this.bookPath, true))
                {
                    StringBuilder input = new StringBuilder();
                    input.Append(newReading.Title + "|" + newReading.Author + "|" + newReading.ECopy + "|" + newReading.IDNumber
                         + "|" + newReading.DepartmentLocation + "|" + newReading.BookGenre);
                    writer.WriteLine(input);
                }
            }
        }

        public void StoreClient(Client newClient)
        {
            bool fileCreated = CreateFileIfNotExists(this.clientPath);
            if (fileCreated)
            {
                using (StreamWriter writer = new StreamWriter(this.clientPath, true))
                {
                    StringBuilder input = new StringBuilder();
                    input.Append(newClient.FirstName + "|" + newClient.LastName + "|" + newClient.EGN + "|" + newClient.Address + "|" + newClient.Taken);
                    writer.WriteLine(input);
                }
            }
        }

        public void StoreTemp(Reading newReading, Client newClient)
        {
            bool fileCreated = CreateFileIfNotExists(this.tenantPath);
            if (fileCreated)
            {
                using (StreamWriter writer = new StreamWriter(this.tenantPath, true))
                {
                    StringBuilder input = new StringBuilder();
                    input.Append(newClient.EGN + "|" + newReading.available + "|" + newReading.EndBorrowPeriod + "|" + newReading.IDNumber);
                    writer.WriteLine(input);
                }
            }
        }

        //public void UpdateTempStore(Reading returnReading)
        //{
        //    using (StreamReader reader = new StreamReader(@"tenantData.txt", Encoding.GetEncoding(1251)))
        //    {
        //        string line = reader.ReadLine();

        //        while (line != null)
        //        {
        //            string[] fields = line.Split('|');

        //            foreach (var field in fields)
        //            {
        //                if (field == returnReading.IDNumber && fields[1] == "false")
        //                {
        //                    fields[1] = "true";
        //                    returnReading.EndBorrowPeriod = default(DateTime);
        //                }
        //            }
        //            line = reader.ReadLine();
        //        }
        //    }
        //}

        public void StoreNewspaper(NewsPaper newReading)
        {
            bool fileCreated = CreateFileIfNotExists(this.newspaperPath);
            if (fileCreated)
            {
                using (StreamWriter writer = new StreamWriter(this.newspaperPath, true))
                {
                    StringBuilder input = new StringBuilder();
                    input.Append(newReading.IDNumber + "|" + newReading.Author + "|" + newReading.DateReleased);
                    writer.WriteLine(input);
                }
            }
        }
        public void StoreMagazine(Magazine newReading)
        {
            bool fileCreated = CreateFileIfNotExists(this.magazinePath);
            if (fileCreated)
            {
                using (StreamWriter writer = new StreamWriter(this.magazinePath, true))
                {
                    StringBuilder input = new StringBuilder();
                    input.Append(newReading.IDNumber + "|" + newReading.Author + "|" + newReading.DateReleased);
                    writer.WriteLine(input);
                }
            }
        }

        public List<Book> LoadBooks()
        {
            List<Book> loadedBooks = new List<Book>();
            Regenerator reg = new Regenerator();

            using (StreamReader booksData = new StreamReader(bookPath))
            {
                string line = booksData.ReadLine();
                while (line != null)
                {
                    string[] values = line.Split('|');
                    string title = values[0];
                    string author = values[1];
                    bool eCopy = reg.StringToBool(values[2]);
                    string id = values[3];
                    Genre genre = reg.StringToGenre(values[5]);
                    DepartmentsName dept = reg.StringToDepartmentsName(values[4]);
                    Book nb = new Book(title, author, eCopy, id, dept, genre);
                    loadedBooks.Add(nb);
                    line = booksData.ReadLine();
                }
            }

            return loadedBooks;
        }

        public List<NewsPaper> LoadNewspapers()
        {
            List<NewsPaper> loadedNewspapers = new List<NewsPaper>();

            using (StreamReader newspaperData = new StreamReader(newspaperPath))
            {
                string line = newspaperData.ReadLine();
                while (line != null)
                {
                    string[] values = line.Split('|');
                    string id = values[0];
                    string author = values[1];
                    string dateReleased = values[2];
                    NewsPaper nnews = new NewsPaper(id, author, dateReleased);
                    loadedNewspapers.Add(nnews);
                    line = newspaperData.ReadLine();
                }
            }

            return loadedNewspapers;
        }
        public List<Magazine> LoadMagazines()
        {
            List<Magazine> loadedMagazines = new List<Magazine>();

            using (StreamReader magazineData = new StreamReader(magazinePath))
            {
                string line = magazineData.ReadLine();
                while (line != null)
                {
                    string[] values = line.Split('|');
                    string id = values[0];
                    string author = values[1];
                    string dateReleased = values[2];
                    Magazine nmag = new Magazine(id, author, dateReleased);
                    loadedMagazines.Add(nmag);
                    line = magazineData.ReadLine();
                }
            }

            return loadedMagazines;
        }

        public List<Client> LoadClients()
        {
            List<Client> loadedClients = new List<Client>();

            using (StreamReader clientsData = new StreamReader(clientPath))
            {
                string line = clientsData.ReadLine();
                while (line != null)
                {
                    string[] values = line.Split('|');
                    string fname = values[0];
                    string lname = values[1];
                    ulong egn = ulong.Parse(values[2]);
                    string address = values[3];
                    Client nc = new Client(fname, lname, egn, address);
                    loadedClients.Add(nc);
                    line = clientsData.ReadLine();
                }
            }

            return loadedClients;
        }

        private bool CreateFileIfNotExists(string p)
        {
            try 
            {
                if (!File.Exists(p))
                {
                    var myFile = File.Create(p);
                    myFile.Close();
                }
                return true;
            }
            catch
            {
                throw new DirectoryNotFoundException("Could not create file!!!");
            }
        }
    }
}
